<template>
    <div class="login-page">
      <validate-form @form-submit="onFormSubmit">
        <div class="mb-3">
          <label class="form-label">邮箱地址</label>
          <validate-input :rules="emailRules" v-model="emailVal" placeholder="请输入邮箱地址" type="text"></validate-input>
        </div>
        <div class="mb-3">
          <label for="exampleInputPassword1" class="form-label">密码</label>
          <validate-input :rules="passwordRules" v-model="passwordVal" placeholder="请输入密码" type="password"></validate-input>
        </div>
        <template #submit>
          <span class="btn btn-danger">Submit</span>
        </template>
    </validate-form>
    </div>
</template>
<script lang="ts">
import { defineComponent,ref} from 'vue'
import {useStore} from 'vuex'
import {useRouter} from 'vue-router'
import ValidateInput,{RulesProp} from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import createMessage from '../components/createMessage'
export default defineComponent({  //发送请求
  name: 'App',
  components:{
    ValidateInput,
    ValidateForm
  },
  setup(){
    const emailVal=ref('')  //数据绑定
    const router = useRouter()  //返回this.$router
    const passwordVal=ref('')  //数据绑定
    const store = useStore()   //返回this.$store
    const emailRules:RulesProp = [
      {type:'required',message:'电子邮箱地址不能为空'},
      {type:'email',message:'请输入正确的电子邮箱格式'}
    ]
    const passwordRules:RulesProp = [
      {type:'required',message:'密码不能为空'},
      {type:'password',message:'请输入正确的密码格式，只能包含数字字母'}
    ]
    const onFormSubmit = (result:boolean)=>{  //从ValidateForm.vue传过来的验证结果值
      if(result){ //输入的规则合法
        const payload={
          email:emailVal.value,
          password:passwordVal.value
        }
        store.dispatch('loginAndFetch',payload).then(data=>{  //调用store.ts中的actions里面的方法，发送请求
          createMessage('登陆成功 1秒后跳转首页','success')
          setTimeout(()=>{
            router.push('/')  //回到首页
          },1000)
        }).catch(e=>{   //登陆不成功不要报红色错误，直接输出即可
          console.log(e)
        })
      }
    }
    // const emailRef = reactive({
    //   val:'',
    //   error:false,
    //   message:''
    // })
    // const validateEmail = ()=>{
    //   if(emailRef.val.trim() ===''){
    //     emailRef.error=true
    //     emailRef.message='can not be empty'
    //   }else if(!emailReg.test(emailRef.val)){
    //     emailRef.error=true
    //     emailRef.message='should be valid email'
    //   }
    // }
    return {
      emailRules,
      emailVal,
      passwordRules,
      passwordVal,
      onFormSubmit,
    }
  }
})
</script>
